# -*- coding:utf-8 -*-
"""
金贝财经
https://www.bcfin.com.cn/
快讯
"""
import requests
from WriteData import writedata
from Tk import genearteMD5
from cs import day


def post_html_text(data):
    url = 'https://www.bcfin.com.cn/index.php/Index/kuaixunajax.shtml'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.post(url, timeout=30, data=data, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.json()
    except Exception as e:
        print(e)


def get_dates_kx(data):
    text = post_html_text(data)
    dates = [date['adddate'] for date in text]
    return dates


def count_process_one():
    datas = dict(d1=0, d2=0, d3=0, d4=0)
    mapping = {
        0: 'd1',
        1: 'd2',
        2: 'd3',
    }
    a = 0
    while a < 50:
        data = {'npage': a}
        dates = get_dates_kx(data)
        if not dates:
            continue
        print('----简一财经快讯获取第{}页----'.format(a + 1))
        for date in dates:
            s = day(date)
            mapp = mapping.get(s) or 'd4'
            datas[mapp] += 1
        a += 1
        if datas['d4'] > 0:
            break
    return (datas.get('d1'), datas.get('d2'), datas.get('d3'))


def main():
    u = '金贝财经'
    t1 = count_process_one()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
